<?php
namespace Home\Controller;

use Think\Controller;

//首页-控制器
class AgentsController extends Controller {

    public $AgentModel;    //代理商
    public $BornNumModel;  //分娩量
    public $HospitalModel;
    public $CityModel;
    public $videoBookModel;

    public function __construct(){
        if(empty(cookie('agentData')) && ACTION_NAME !='agent_login'){
            redirect('/agents/agent_login');
        }
        
        parent::__construct();
        $this->AgentModel      = D('Agent');                   //代理商
        $this->BornNumModel    = D('HospitalBornNumber');      //分娩量
        $this->HospitalModel   = D('Hospital');
        $this->CityModel       = D('City');
        $this->videoBookModel  = D('videoBook');
    }

    /**
     * [startAndEndtime 根据时间参数，计算月初和月末两个时间]
     * @author xiezy
     * @date   2018-05-29
     * @param  [type]     $time [description]
     * @return [type]           [description]
     */
    private static function startAndEndtime($time){
        date_default_timezone_set('Asia/Shanghai');

        $y  =   date("Y",$time);
        $m  =   date("m",$time);
        $d  =   date("d",$time);
        $t  =   date('t',$time);                  // 本月一共有几天
        $t1 =   mktime(0,0,0,$m,1,$y);            // 创建本月开始时间
        $t2 =   mktime(23,59,59,$m,$t,$y);        // 创建本月结束时间

        return array('start_time'=>$t1,'end_time'=>$t2);
    }

    /**
     * [takeStartTime 算出过去7天和30天]
     * @author xiezy
     * @date   2018-06-02
     * @return $time     [今天的时间戳]
     */
    private static function takeStartTime($time,$day=7){
        date_default_timezone_set('Asia/Shanghai');

        return  $time - $day * 24 * 60 * 60;
    }

    /**
     * [login 登录页面]
     * @author xiezy
     * @date   2018-05-31
     * @return [type]     [description]
     */
    public function agent_login(){
        // 登录页面
        if (IS_GET) {
            $this->display();
        }

        //登录操作
        if (IS_POST) {
            $priceWhere['agent_name']            = I('post.agent_name');
            $priceWhere['agent_password']        = md5( I('post.agent_password') );
            $agentData                           = $this->AgentModel->where($priceWhere)->find();

            if ( !empty($agentData) ) {
                unset($agentData['agent_password']);
                cookie('agentData',$agentData);     //存代理商数据

                $returndata['status'] = 1;
                $returndata['info']   = '登录成功';
                $returndata['url']    = U(MODULE_NAME.'/agents/cartogram');
                $this->ajaxReturn($returndata);
            }else{
                $returndata['status'] = 0;
                $returndata['info']   = '登录失败';
                $this->ajaxReturn($returndata);
            }
        }
    }

    /**
     * [cityDeliveryNum 城市分娩量]
     * @author xiezy
     * @date   2018-06-03
     *         $cityArray       城市ID集合 【数组】
     *         $day             过去天数   【暂定7天和30天】
     * @return [type]     [description]
     */
    public function cityDeliveryNum($cityArray,$day){
        //往前推算$day天的时间戳
        $lastDayTime           = static::takeStartTime(time(),$day);            //跨月-往上个月的起始日时间戳 算出过去7天或30天的时间戳
        //根据推算的$day天前的时间戳，获取日期,从而得到医院分娩记录数组的下标
        $lastDay               = date('j',$lastDayTime);                        //跨月-往上个月的起始日       例如：5月27号 => 27
        $nowDay                = date('j',time());                              //这个月的今天                例如：6月03号 => 3
        $lastTimeData          = static::startAndEndtime($lastDayTime);         //起始日 --- 月初、月末时间戳
        $nowTimeData           = static::startAndEndtime(time());               //结束日 --- 月初、月末时间戳

        foreach ($cityArray as $key => $val) {
            //城市名字
            $whereOne['CityID']     = $val;
            $city_name              = $this->CityModel->where($whereOne)->getField('cityname');
            $cityDelData[$val]['city_name'] = $city_name;
            //多城市名字对应的分娩量
            $whereTwo['city_id'] = $val;
            $cityHospitalData = $this->HospitalModel->where($whereTwo)->select();
            //设置初始值
            $cityDelData[$val]['del_num'] = '0';
            foreach ($cityHospitalData as $k => $v) {
                if ($lastTimeData['start_time'] == $nowTimeData['start_time']) {
                    //同一个月内
                    $whereTree['hospital_id'] = $v['id'];
                    $whereTree['start_time']  = array("eq",$nowTimeData['start_time']);
                    $whereTree['end_time']    = array("eq",$nowTimeData['end_time']);

                    $BornNumData = $this->BornNumModel->where($whereTree)->find();
                    $BornNumData['count_born_num'] = unserialize($BornNumData['count_born_num']);
                    foreach ($BornNumData['count_born_num'] as $kb => $vb) {
                        if ($kb >= $lastDay && $kb<$nowDay){ //7天的分娩量
                            $cityDelData[$val]['del_num'] += $vb['num'];
                        }
                    }
                }else{
                    //起始月
                    $whereFour['hospital_id'] = $v['id'];
                    $whereFour['start_time']  = array("eq",$lastTimeData['start_time']);
                    $whereFour['end_time']    = array("eq",$lastTimeData['end_time']);
                    $lastBornNumData = $this->BornNumModel->where($whereFour)->find();
                    $lastBornNumData['count_born_num'] = unserialize($lastBornNumData['count_born_num']);
                    foreach ($lastBornNumData['count_born_num'] as $klb => $vlb) {
                        if ($klb >= $lastDay){ //7天的分娩量
                            $cityDelData[$val]['del_num'] += $vlb['num'];
                        }
                    }
                    //中间月
                    $lastDayMonth          = date('m',$lastDayTime);                        //跨月-起始日的月份           5月 => 5
                    $nowDay_2Month         = date("m",strtotime("-2 month") );              //跨月-结束日前2个月的月份    6月 => 6
                    //特殊情况 跨2个月
                    if ( $day==30 && $lastDayMonth == $nowDay_2Month) {
                        $midDay                   = strtotime("-1 month");                  //中间月 --- 月中时间戳
                        $midTimeData              = static::startAndEndtime($midDay);       //中间月 --- 月初、月末时间戳

                        $whereFive['hospital_id'] = $v['id'];
                        $whereFive['start_time']  = array("eq",$midTimeData['start_time']);
                        $whereFive['end_time']    = array("eq",$midTimeData['end_time']);
                        $midBornNumData = $this->BornNumModel->where($whereFive)->find();
                        $midBornNumData['count_born_num'] = unserialize($midBornNumData['count_born_num']);
                        foreach ($midBornNumData['count_born_num'] as $kmb => $vmb) {
                            $cityDelData[$val]['del_num'] += $vmb['num'];
                        }
                    }

                    //结束月
                    $whereFour['hospital_id'] = $v['id'];
                    $whereFour['start_time']  = array("eq",$nowTimeData['start_time']);
                    $whereFour['end_time']    = array("eq",$nowTimeData['end_time']);
                    $nowBornNumData = $this->BornNumModel->where($whereFour)->find();
                    $nowBornNumData['count_born_num'] = unserialize($nowBornNumData['count_born_num']);
                    foreach ($nowBornNumData['count_born_num'] as $knb1 => $vnb) {
                        if ($knb1 < $nowDay){ //7天的分娩量
                            $cityDelData[$val]['del_num'] += $vnb['num'];
                        }
                    }
                }
            }
        }
//         p($cityDelData);
        foreach($cityDelData as $cdkey => $cdval){
            //拼接前端需要的数组
            $cityNameList[$cdkey] = $cdval['city_name'];
            
            $cityBronList[$cdkey]['value'] = $cdval['del_num'];
            $cityBronList[$cdkey]['name'] = $cdval['city_name'];
        }
        $returnData[0] = array_merge($cityNameList);
        $returnData[1] = array_merge($cityBronList);
        //返回城市数组（城市名，分娩量）
        return $returnData;
    }
    /**
     * [cityOrderNum 获取城市的订单量]
     * @author Lin
     * @date   2018-06-04
     * @return [type]     [description]
     */
    public function cityOrderNum($cityArray,$day){
        $toDay       = strtotime(date('Y-m-d', time()));
        $lastDayTime = $toDay - $day * 24 * 60 * 60;
        $nowDayTime  = $toDay + 24 * 60 * 60 -1;
        foreach ($cityArray as $key => $val) {
            $cityWhere['CityID'] = $val;
            $orderWhere['_string'] = 'CityId = '.$val.' and create_time >'.$lastDayTime.' and create_time <'.$nowDayTime;
            //获取城市信息
            $cityInfo = $this->CityModel->field('cityid,cityname')->where($cityWhere)->find();
            //获取订单数量
            $cityOrderCount['count'] = $this->videoBookModel->where($orderWhere)->count();
            //合并数组
            $cityOrderData[$key] = array_merge($cityInfo,$cityOrderCount);
        }

        foreach($cityOrderData as $cokey => $coval){
            $cityNameList[$cokey] = $coval['cityname'];

            $cityOrderNum[$cokey]['value'] = $coval['count'];
            $cityOrderNum[$cokey]['name'] = $coval['cityname'];
        }
        $returnData[0] = array_merge($cityNameList);
        $returnData[1] = array_merge($cityOrderNum);
        //返回城市数组（城市名，分娩量）
        return $returnData;
    }

    /**
     * [hospitalOrderNum 获取医院的订单量]
     * @author Lin
     * @date   2018-06-04
     * @param  [type]     $city_id [description]
     * @param  [type]     $day     [description]
     * @return [type]              [description]
     */
    public function hospitalOrderNum($city_id,$day){
        $toDay = strtotime(date('Y-m-d', time()));
        $lastDayTime = $toDay - $day * 24 * 60 * 60;
        $nowDayTime = $toDay + 24 * 60 * 60 -1;

        $hospitalList = $this->HospitalModel->field('id,province_id,city_id,hospital_name,hospital_price')->where('city_id = '.$city_id)->select();
        foreach($hospitalList as $hkey => $hval){
            $orderWhere['_string'] = 'hospitalId = '.$hval['id'].' and create_time >'.$lastDayTime.' and create_time <'.$nowDayTime;
            //获取订单数量
            $hospitalList[$hkey]['count'] = $this->videoBookModel->where($orderWhere)->count();

            $cityToHospitalName['city_name'] = $this->CityModel->where('CityID = '.$hval['city_id'])->getField('CityName');
            $hospitalNameList[$hkey] = $hval['hospital_name'];
            $hospitalOrderNum[$hkey] = $hospitalList[$hkey]['count'];
        }
        $returnData[0] = array_merge($cityToHospitalName);
        $returnData[1] = array_merge($hospitalNameList);
        $returnData[2] = array_merge($hospitalOrderNum);
        return $returnData;
    }
    
    /**
     * [hospitalOrderNum 获取医院的分娩量]
     * @author Lin
     * @date   2018-06-06
     * @param  [type]     $city_id [description]
     * @param  [type]     $day     [description]
     * @return [type]              [description]
     */
    public function hospitalDeliveryNum($city_id,$day){
        //往前推算$day天的时间戳
        $lastDayTime           = static::takeStartTime(time(),$day);            //跨月-往上个月的起始日时间戳 算出过去7天或30天的时间戳
        //根据推算的$day天前的时间戳，获取日期,从而得到医院分娩记录数组的下标
        $lastDay               = date('j',$lastDayTime);                        //跨月-往上个月的起始日       例如：5月27号 => 27
        $nowDay                = date('j',time());                              //这个月的今天                例如：6月03号 => 3
        $lastTimeData          = static::startAndEndtime($lastDayTime);         //起始日 --- 月初、月末时间戳
        $nowTimeData           = static::startAndEndtime(time());               //结束日 --- 月初、月末时间戳
        
        //搜索城市下面的医院
        $cityToHopitalWhere['city_id'] = $city_id;
        $cityHospitalData = $this->HospitalModel->where($cityToHopitalWhere)->select();
        //城市-医院对应的分娩量
        foreach($cityHospitalData as $chkey => $chval){
            $hospitalDelData[$chkey]['hospital_name'] = $chval['hospital_name'];
            if ($lastTimeData['start_time'] == $nowTimeData['start_time']) {
                //同一个月内
                $whereTree['hospital_id'] = $chval['id'];
                $whereTree['start_time']  = array("eq",$nowTimeData['start_time']);
                $whereTree['end_time']    = array("eq",$nowTimeData['end_time']);

                $BornNumData = $this->BornNumModel->where($whereTree)->find();
                $BornNumData['count_born_num'] = unserialize($BornNumData['count_born_num']);
                foreach ($BornNumData['count_born_num'] as $kb => $vb) {
                    if ($kb >= $lastDay && $kb<$nowDay){ //7天的分娩量
                        $hospitalDelData[$chkey]['del_num'] += $vb['num'];
                    }
                }
            }else{
                    //起始月
                    $whereFour['hospital_id'] = $chval['id'];
                    $whereFour['start_time']  = array("eq",$lastTimeData['start_time']);
                    $whereFour['end_time']    = array("eq",$lastTimeData['end_time']);
                    $lastBornNumData = $this->BornNumModel->where($whereFour)->find();
                    $lastBornNumData['count_born_num'] = unserialize($lastBornNumData['count_born_num']);
                    foreach ($lastBornNumData['count_born_num'] as $klb => $vlb) {
                        if ($klb >= $lastDay){ //7天的分娩量
                            $hospitalDelData[$chkey]['del_num'] += $vlb['num'];
                        }
                    }
                    //中间月
                    $lastDayMonth          = date('m',$lastDayTime);                        //跨月-起始日的月份           5月 => 5
                    $nowDay_2Month         = date("m",strtotime("-2 month") );              //跨月-结束日前2个月的月份    6月 => 6
                    //特殊情况 跨2个月
                    if ( $day==30 && $lastDayMonth == $nowDay_2Month) {
                        $midDay                   = strtotime("-1 month");                  //中间月 --- 月中时间戳
                        $midTimeData              = static::startAndEndtime($midDay);       //中间月 --- 月初、月末时间戳

                        $whereFive['hospital_id'] = $chval['id'];
                        $whereFive['start_time']  = array("eq",$midTimeData['start_time']);
                        $whereFive['end_time']    = array("eq",$midTimeData['end_time']);
                        $midBornNumData = $this->BornNumModel->where($whereFive)->find();
                        $midBornNumData['count_born_num'] = unserialize($midBornNumData['count_born_num']);
                        foreach ($midBornNumData['count_born_num'] as $kmb => $vmb) {
                            $hospitalDelData[$chkey]['del_num'] += $vmb['num'];
                        }
                    }

                    //结束月
                    $whereFour['hospital_id'] = $chval['id'];
                    $whereFour['start_time']  = array("eq",$nowTimeData['start_time']);
                    $whereFour['end_time']    = array("eq",$nowTimeData['end_time']);
                    $nowBornNumData = $this->BornNumModel->where($whereFour)->find();
                    $nowBornNumData['count_born_num'] = unserialize($nowBornNumData['count_born_num']);
                    foreach ($nowBornNumData['count_born_num'] as $knb1 => $vnb) {
                        if ($knb1 < $nowDay){ //7天的分娩量
                            $hospitalDelData[$chkey]['del_num'] += $vnb['num'];
                        }
                    }
                }
        }
        foreach($hospitalDelData as $hdkey => $hdval){
            $hospitalNameList[$hdkey] = $hdval['hospital_name'];
        
            $hospitalDelList[$hdkey]  = $hdval['del_num'];
        }
        $returndata[0] = array_merge($hospitalNameList);
        $returndata[1] = array_merge($hospitalDelList);
        $returndata[2] = $this->CityModel->where('CityID = '.$city_id)->getField('CityName');
        return $returndata;
    }

    /**
     * [cartogram 统计图（简）]
     * @author xiezy
     * @date   2018-06-02
     * @return [type]     [description]
     */
    public function cartogram(){
        //1.获取代理商代理的所有城市-饼图数据    【默认过去7天的数据】
        $agentData = cookie('agentData');
        //获取城市ID集合
        $cityData  = explode(',', $agentData['city_id']);
        foreach($cityData as $ckey =>$cval){
            $cityList[$ckey] = $this->CityModel->field('cityid,cityname')->where('CityID = '.$cval)->find();
        }
        //获取城市数组（城市名，分娩量）[饼图]
        $cityDelData = $this->cityDeliveryNum($cityData,7);
        //获取城市订单数组[饼图]
        $cityOrderData = $this->cityOrderNum($cityData,7);
        //2.获取代理商城市所有医院的订单数据【柱状图】【默认第一个城市】
        $hospitalOrderData = $this->hospitalOrderNum($cityData[0],7);
        //获取代理商对应城市的医院分娩量数据【柱状图】【默认第一个城市】
        $hospitalDelData = $this->hospitalDeliveryNum($cityData[0],7);
//         p($hospitalDelData);
        //城市列表
        $this->assign('citylist',$cityList);
        //城市分娩量数据[饼图]
        $this->assign('cityNameList',json_encode($cityDelData[0], JSON_UNESCAPED_UNICODE));   //城市-名字，分娩量
        $this->assign('cityBronList',json_encode($cityDelData[1], JSON_UNESCAPED_UNICODE));   //城市-名字，分娩量
        //城市订单数据[饼图]
        $this->assign('cityOrderNameList',json_encode($cityOrderData[0], JSON_UNESCAPED_UNICODE));   //城市-名字，分娩量
        $this->assign('cityOrderNumList',json_encode($cityOrderData[1], JSON_UNESCAPED_UNICODE));   //城市-名字，分娩量
        //城市-医院订单数据【柱状图】
        $this->assign('cityNameString',$hospitalOrderData[0]['city_name']);
        $this->assign('cityName',json_encode($hospitalOrderData[0], JSON_UNESCAPED_UNICODE));
        $this->assign('cityToHopitalName',json_encode($hospitalOrderData[1], JSON_UNESCAPED_UNICODE));
        $this->assign('cityToHopitalOrderNum',json_encode($hospitalOrderData[2], JSON_UNESCAPED_UNICODE));
        //城市-医院分娩数据【柱状图】
        $this->assign('hospitalNameString',$hospitalDelData[2]);
        $this->assign('hospitalName',json_encode($hospitalDelData[0], JSON_UNESCAPED_UNICODE));
        $this->assign('hospitalDelNum',json_encode($hospitalDelData[1], JSON_UNESCAPED_UNICODE));
        $this->assign('hospitalToCityName',json_encode($hospitalDelData[2], JSON_UNESCAPED_UNICODE));
        $this->display();
    }

    /**
     * [getCartoForDate 根据日期获取对应的数据]
     * @author xiezy
     * @date   2018-06-02
     * @return [type]     [description]
     */
    public function getCartoForDate(){
        $agentData = cookie('agentData');
        //获取城市ID集合
        $cityData  = explode(',', $agentData['city_id']);
        $day = I('post.last_day');
        $city_id = I('post.city_id');
        //获取城市数组（城市名，分娩量）[饼图]
        $cityDelData = $this->cityDeliveryNum($cityData,$day);
        //获取城市订单数组[饼图]
        $cityOrderData = $this->cityOrderNum($cityData,$day);
        //2.获取代理商城市所有医院的数据【柱状图】【默认第一个城市】
        $hospitalOrderData = $this->hospitalOrderNum($city_id,$day);
        //获取代理商对应城市的医院分娩量数据【柱状图】【默认第一个城市】
        $hospitalDelData = $this->hospitalDeliveryNum($city_id,$day);

        $info['status'] = 1;
        $info['msg'] = '成功';
        $info['cityNameList']           = $cityDelData[0];//json_encode($cityDelData[0], JSON_UNESCAPED_UNICODE);
        $info['cityBronList']           = $cityDelData[1];//json_encode($cityDelData[1], JSON_UNESCAPED_UNICODE);
        $info['cityOrderNameList']      = $cityOrderData[0];//json_encode($cityOrderData[0], JSON_UNESCAPED_UNICODE);
        $info['cityOrderNumList']       = $cityOrderData[1];//json_encode($cityOrderData[1], JSON_UNESCAPED_UNICODE);
        $info['cityNameString']         = $hospitalOrderData[0]['city_name'];
        $info['cityName']               = $hospitalOrderData[0];
        $info['cityToHopitalName']      = $hospitalOrderData[1];
        $info['cityToHopitalOrderNum']  = $hospitalOrderData[2];
        $info['hospitalNameString']     = $hospitalDelData[2];
        $info['hospitalName']           = $hospitalDelData[0];
        $info['hospitalDelNum']         = $hospitalDelData[1];
        $info['hospitalToCityName']     = $hospitalDelData[2];
        $this->ajaxReturn($info ,'json');
    }

}
